import { exec } from 'node:child_process';
import { read, write, readNext, writeNext } from './jsonData.js';
import { isNumericString } from '../common.js';

import { createInterface, emitKeypressEvents } from 'node:readline';

const args_1 = process.argv.slice(2)[0];

// 荣耀机
// const device = 'A9QLVB2219003636';

// iqoo无线调试
// const device = 'adb-10AD5N2AL1000UX-wt6zpI._adb-tls-connect._tcp';

// 有线
const device = '10AD5N2AL1000UX';
 

// 速搜
const folderPath = '/storage/sdcard0/Android/data/com.sjz.ss/files/video/Download'; // 替换为你要查看的文件夹路径

// 速搜分身
// const folderPath = '/storage/sdcard0/Android/data/com.qihoo.magic.dzNnL6pmLt92Yk_101/101/Android/data/com.jz.ss/files/video/Download'; // 替换为你要查看的文件夹路径

// 影视工场
// const folderPath = '/storage/emulated/0/Android/data/xyz.penghaonan.smartdrawer.sht/files/video_download';

// 操作 先不传参数弄一遍
// 然后每删一集 就把集数传进来

// 要执行的adb shell命令
// const adbCommand = 'adb shell ls /';

// 得到adb数据(输出数组)
const getAdbData = () => {
    return new Promise(resolve => {
        exec('adb start-server', (error, stdout, stderr) => {
            if (error) {
                console.error(`Error starting ADB server: ${error}`);
                return;
            }

            // 查看已连接的设备
            exec('adb devices', (error, stdout, stderr) => {
                if (error) {
                    console.error(`Error listing devices: ${error}`);
                    return;
                }
                console.log(`Connected devices: ${stdout}`);

                // 假设你已经连接了设备并且设备状态为"device"
                // 进入设备的Shell并查看文件夹内容

                exec(`adb -s ${device} shell ls ${folderPath}`, async (error, stdout, stderr) => {
                    if (error) {
                        console.error(`Error listing folder content: ${error}`);
                        return;
                    }

                    const wa = stdout.split('\r\n').filter(item => item);

                    // 如果是影视工场，过滤出-m3u8的文件夹，只需要字符串名即可
                    const was = wa.filter(item => !item.endsWith('-m3u8'));

                    console.log('adb得到多少个===>', was.length);
                    resolve(was);
                });
            });
        });
    });
};

// 更新
const update = async (key, value) => {
    const readAll = await read();
    if (Object.hasOwn(readAll, key)) {
        console.log(`存在该属性${key}，原值为==>`, readAll[key], '，更新为==>', value);
    } else {
        console.log(`不存在该属性${key}`, '新增为==>', value);
    }
    readAll[key] = value;
    const res = await write(readAll);
    console.log(res);
};

// 如果没有参数（集数）传进来，那么就是初始化
const doInit = async () => {
    // 现有有值的
    const readTrue = await read(true);

    const adbData = await getAdbData();

    // 注意，新值会覆盖旧值
    const res = await write({ ...readTrue, ...Object.fromEntries(adbData.map(key => [key, ''])) });

    if (res === 'success') {
        console.log(res, '请注意文件提前复制出来，才删除哦。');
    }
};

// 如果是字符串，则得出里面的数字加1
const processInput = (param1, param2) => {
    // 如果第一个参数是数字
    if (isNumericString(param1)) {
        return parseInt(param1 + '', 10) + param2;
    } else {
        // 找出字符串中的第一个数字
        const match = param1.match(/\d+/);
        const numStr = match[0];
        const firstNumber = match ? parseInt(numStr, 10) : 0;

        // 计算结果
        const result = firstNumber + param2;

        // 替换字符串中的第一个数字
        const newString = param1.replace(numStr, result.toString());

        return newString;
    }

    // 如果第一个参数既不是数字也不是字符串，返回 null 或抛出错误
    return null;
};

// 如果有集数传进来，就说明是更新态
const doToData = async args_1 => {
    const adbData = await getAdbData();

    // 算出被删的那一个
    const obj = await read(false);
    const res = Object.keys(obj).filter(item => !adbData.includes(item));

    let updateNum;

    if (args_1 === 'next') {
        const nextNow = await readNext();
        updateNum = nextNow.next;
    } else {
        updateNum = args_1;
    }

    const now = updateNum;
    const next = processInput(now, 1);
    if (res.length === 1) {
        const nextObj = {
            now,
            next
        };
        update(res[0], updateNum);
        writeNext(nextObj);
        console.log('记录next==>', nextObj);
    } else {
        console.log('其他情况', res);
        return;
    }
};

const enter = () => {
    // 创建 readline 接口
    const rl = createInterface({
        input: process.stdin,
        output: process.stdout
    });

    // 监听按键事件
    process.stdin.on('keypress', (str, key) => {
        if (key.ctrl && key.name === 'c') {
            console.log('检测到Ctrl+C, 执行退出...');
            process.exit();
        } else {
            if (str === 'm' || str === '0') {
                // console.log(str)
                doToData('next');
            }
        }
    });

    // 启用原始模式以捕获按键事件
    emitKeypressEvents(process.stdin);
    if (process.stdin.isTTY) {
        process.stdin.setRawMode(true);
    }
};

if (!args_1) {
    doInit();
} else if (args_1 === 'en') {
    enter();
} else {
    doToData(args_1);
}
